import api from '../../api';
import { switchMenu } from '../../utils/utils';

export default {
  namespace: 'menuManage',

  state: {
    menuList: [],
    rolesList: [],
  },

  effects: {
    *addMenu({ payload }, { call, put }) {
      const response = yield call(api.menuManage.addMenu, payload);
      yield put({
        type: 'fetchMenuList',
        payload: {},
      });
    },
    *updateMenu({ payload }, { call, put }) {
      const response = yield call(api.menuManage.updateMenu, payload);
      yield put({
        type: 'fetchMenuList',
        payload: {},
      });
    },
    *fetchRoles({ payload }, { call, put }) {
      const response = yield call(api.menuManage.fetchRoles, payload);
      const rolesList = [{ key: '0', value: '全部' }];

      if (response.success) {
        for (let [key, value] of Object.entries(response.data)) {
          rolesList.push({ key: key.toString(), value });
        }
      }

      yield put({
        type: 'save',
        payload: {
          rolesList,
        },
      });
    },
    *deleteMenu({ payload }, { call, put }) {
      const response = yield call(api.menuManage.deleteMenu, payload);
    },
    *fetchMenuList({ payload }, { call, put }) {
      const response = yield call(api.menuManage.fetchMenuList, payload);
      const menu = switchMenu([response]);

      yield put({
        type: 'save',
        payload: {
          menuList: menu,
        },
      });
    },
  },

  reducers: {
    save(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};
